<template>
  <div class="user-mana">
    <unfold>
      <!-- 左侧树状列表 -->
      <template v-slot:tree-list>
        <tree-list
          ref="departmentsTree"
          head-name="部门列表"
          head-icon="iconfont icontubiao-36"
          :list="departments"
          @getTree="getDepartmentsTree"
          @setAct="onDepartmentSelect"
          isDisOpen
          isAll
        />
        <!--          edit-url="depart-list"-->
      </template>
      <!-- 右侧 card -->
      <template v-slot:content>
        <div class="relative-position full-height page-content">
          <collapse ref="collapse">
            <template v-slot:content>
              <q-form class="toolbar" @submit.prevent="onSearchByFilters()" style="margin-top: 6px">
                <!-- 工具栏上层 -->
                <div class="form-inline top">
                  <div class="left box">
                  <select-tooltip
                        v-model="queryParams.role"
                        :multiple="false"
                        isShowAll
                        :options="roleOptions"
                        msg="角色"
                  />
                  <select-tooltip
                        v-model="queryParams.post"
                        :multiple="false"
                        isShowAll
                        :options="postOptions"
                        msg="岗位"
                  />
                    <q-select
                      class="select"
                      v-if="false"
                      outlined dense emit-value map-options options-dense
                      :options="statusOptions"
                      v-model="queryParams.status"
                    >
                      <template v-slot:before>
                        <span class="form-name">状态:</span>
                      </template>
                    </q-select>
                  </div>
                  <div class="right box">
                    <q-btn
                      class="btn margin-r-10"
                      outline
                      color="primary"
                      @click="resetSearch"
                      label="重置"
                    />
                    <q-btn class="btn" unelevated type="submit" color="primary" label="查询" />
                  </div>
                </div>

                <!-- 工具栏下层 -->
                <div class="form-inline bottom">
                  <div class="left box">
                    <q-btn
                      class="btn"
                      outline color="primary"
                      :disable="selectedUsers.length === 0"
                      @click="onBatchDeleteClick"
                      v-show="false"
                      v-if="!isHuawei"
                    >
<!--                      v-has="{id: Enums.SYS_PERMISSION.DELETE_USER_BTN.value}"-->

                      批量删除
                    </q-btn>
                    <q-btn
                      class="btn"
                      outline color="primary"
                      @click="onCreateUserClick"
                      v-if="!isHuawei"
                    >
<!--                      v-has="{id: Enums.SYS_PERMISSION.ADD_USER_BTN.value}"-->
                      新增
                    </q-btn>
<!--                    <q-btn-->
<!--                      class="btn"-->
<!--                      outline color="primary"-->
<!--                      :disable="selectedUsers.length === 0"-->
<!--                      v-stat="{id:'dlp010307',name:'工位设置'}"-->
<!--                      @click="showWorkCenterSetting = true"-->
<!--                    >-->
<!--                      工位设置-->
<!--                    </q-btn>-->
                    <q-btn
                      class="btn"
                      outline color="primary"
                      :disable="selectedUsers.length === 0"
                      v-stat="{id:'dlp010308',name:'角色设定'}"
                      @click="showRoleSetting = true"
                    >
                      角色设定
                    </q-btn>
                    <download-btn v-if="!isHuawei" :url="downloadUrl" fileName="用户信息表(模板).xls" />
<!--                    :permission="Enums.SYS_PERMISSION.ADD_USER_BTN.value"-->
                    <upload-btn v-if="!isHuawei" :url="uploadUrl" @refresh="listUsers" />
<!--                    v-has="{id: Enums.SYS_PERMISSION.ADD_USER_BTN.value}"-->
                    <export-btn
                      v-if="!isHuawei"
                      label="导出"
                      :exportFun="exportUrl"
                      :exportParams="queryParams"
                      :exportName="`用户列表.xls`"
                    />
                  </div>
                    <select-input ref="selectInput"
                                  :list="queryConditions"
                                  @search="onSearchByKeyword"
                                  class="margin-r-0 right"
                                  @clearSearchVal="clearSearchVal"
                    />
                </div>
              </q-form>
            </template>
          </collapse>
          <!-- 表格 -->
          <q-table
            class="users-table myTable stick-last-col scroll"
            :columns="tableColumns"
            :data="users"
            row-key="id"
            :loading="isTableLoading"
            :pagination.sync="pagination"
            flat
            selection="multiple"
            :selected.sync="selectedUsers"
            color="primary"
            :hide-bottom="!!users.length"
          >
            <template v-slot:body-cell-__index="props">
              <q-td style="width: 80px">{{props.row.__index + 1}}</q-td>
            </template>
            <template v-slot:body-cell-roles="props">
              <q-td>
                {{ getRoleNamesByRoles(props.row.roles) !== '' ? getRoleNamesByRoles(props.row.roles) : '--'  }}
                <q-tooltip>{{ getRoleNamesByRoles(props.row.roles) !== '' ? getRoleNamesByRoles(props.row.roles) : '--' }}</q-tooltip>
              </q-td>
            </template>
            <template v-slot:body-cell-post="props">
              <q-td>{{ getPostNameByCode(props.row.postCode) ? getPostNameByCode(props.row.postCode) : '--' }}</q-td>
            </template>
            <template v-slot:body-cell-gender="props">
              <q-td>{{ getGenderNameByCode(props.row.genderCode) }}</q-td>
            </template>
            <template v-slot:body-cell-skillLevelCode="props">
              <q-td>{{ skillLevelOptions.find(v=>v.value === props.row.skillLevelCode) ? skillLevelOptions.find(v=>v.value === props.row.skillLevelCode).label : '--' }}</q-td>
            </template>
            <template v-slot:body-cell-createTime="props">
              <q-td>{{ props.row.createTime | toTime }}</q-td>
            </template>
            <template v-slot:body-cell-operations="props">
              <q-td class="operations" style="width: 92px">
                <div class="btn-group">
                  <table-btn btnType="detail" @click="onViewUserClick(props.row)"/>
                  <table-btn btnType="edit" @click="onEditUserClick(props.row)"/>
                  <table-btn btnType="other" icon="icontubiao4-50" tooltip="人机绑定信息" @click="getBindList([props.row.id], true)"/>
                  <table-btn btnType="delete" @click="onDeleteClick(props.row.id)"/>
                  <q-toggle
                    v-if="false"
                    v-model="props.row.statusCode"
                    :true-value="statusToggleTrueVal"
                    :false-value="statusToggleFalseVal"
                    checked-icon="iconfont icontubiao-49"
                    unchecked-icon="iconfont icontubiao-48"
                    color="positive"
                    :disable="isStatusToggleDisabled[props.row.id]"
                    @input="onStatusToggle(props.row, $event)"
                  >
                    <template v-slot>
                      <q-tooltip>{{ getStatusToggleTip(props.row.statusCode) }}</q-tooltip>
                    </template>
                  </q-toggle>
                </div>
              </q-td>
            </template>
          </q-table>
          <pagination
            v-model="pagination.page"
            :page-size="pagination.rowsPerPage"
            :total="pagination.rowsNumber"
            @changePageSize="onPageSizeChange"
            @changePage="onPageChange"
          />
        </div>

        <!-- 添加 / 编辑 / 查看详情 dialog -->
        <add-edit-user
          :for-create="userDetailDialog.forCreate"
          :for-edit="userDetailDialog.forEdit"
          :show="userDetailDialog.show"
          :detail="userDetailDialog.detail"
          :departments-tree="departmentsClone"
          :post-options="postOptions.filter(opt => opt.value !== null && opt.enableFlag)"
          :role-options="roleOptions.filter(opt => opt.value !== null)"
          :gender-options="genderOptions"
          :skill-level-options="skillLevelOptions.filter(opt => opt.value !== null && opt.enableFlag)"
          @close="onDetailClose"
          @submitted="onDetailSubmitted"
        />
        <!-- 添加 / 编辑 / 查看详情 dialog -->
        <user-detail
          ref="userDetail"
          :detail="userDetailDialog.detail"
          :departments-tree="departmentsClone"
          :post-options="postOptions.filter(opt => opt.value !== null && opt.enableFlag)"
          :role-options="roleOptions.filter(opt => opt.value !== null)"
          :gender-options="genderOptions"
          :skill-level-options="skillLevelOptions.filter(opt => opt.value !== null && opt.enableFlag)"
          @close="onDetailClose"
          @submitted="onDetailSubmitted"
        />

        <!-- 设置工位 dialog -->
        <work-center-setting
          :show="showWorkCenterSetting"
          :selected-users="selectedUsers"
          @close="showWorkCenterSetting = false"
          @submitted="onWorkCentersSet"
        />

        <!-- 设置角色 dialog -->
        <role-setting
          :show="showRoleSetting"
          :selected-users="selectedUsers"
          :roles="roleOptions.filter(opt => opt.value !== null)"
          @close="showRoleSetting = false"
          @submitted="onRolesSet"
        />
      </template>
    </unfold>
  </div>
</template>

<script>
import userManageApi from 'src/boot/system/user-manage'
import roleDefineApi from 'src/boot/system/role-define'
import { getDict } from 'src/boot/common/dict'
import Unfold from 'src/components/unfold'
import TreeList from 'src/components/tree-list/list'
import Pagination from 'src/components/pagination'
import UserDetail from './components/user-detail'
import addEditUser from './components/add-edit-user'
import WorkCenterSetting from './components/work-center-setting'
import RoleSetting from './components/role-setting'
import SelectInput from 'src/components/select-input'
import Collapse from 'src/components/collapse'
import { downloadUser } from 'src/boot/template/template-download'
import { uploadUser, exportUser } from 'src/boot/template/template-upload'
import { mapGetters } from 'vuex'
import _ from 'lodash'
export default {
  name: 'user-mana',
  components: {
    Unfold,
    TreeList,
    Pagination,
    UserDetail,
    WorkCenterSetting,
    RoleSetting,
    SelectInput,
    Collapse,
    addEditUser
  },
  computed: {
    ...mapGetters([
      'client',
      'userDetail',
      'userInfo'
    ]),
    isHuawei () {
      return this.userInfo.channel === 'hw' && this.userInfo.client_id === 'huawei_iot_stage_app'
    }
  },
  data () {
    return {
      downloadUrl: downloadUser,
      uploadUrl: uploadUser,
      exportUrl: exportUser,
      statUser: [{ value: null, label: '全部' }],
      // 角色选项
      roleOptions: [{ value: null, label: '全部' }],
      // 角色正在加载
      isRoleOptionsLoading: false,

      // 岗位选项
      postOptions: [{ value: null, label: '全部' }],
      // 岗位正在加载
      isPostOptionsLoading: false,

      // 状态选项
      statusOptions: [
        { value: null, label: '全部' },
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' }
      ],

      // 性别选项
      genderOptions: [
        { value: 0, label: '--' },
        { value: 1, label: '男' },
        { value: 2, label: '女' }
      ],

      // 技能水平选项
      skillLevelOptions: [],

      // 查询参数
      queryParams: {
        // 部门 ID
        departmentId: null,
        // 角色 ID
        role: 'all',
        // 岗位
        post: 'all',
        // 状态
        status: null,
        // 搜索依据（关键字类型）
        searchBy: '',
        // 关键字
        keyword: ''
      },

      // 关键字查询条件
      queryConditions: [
        { id: 'number', name: '员工编号', statId: this.CommonConfig.statData.userMana.searchByNum.id },
        { id: 'name', name: '姓名', statId: this.CommonConfig.statData.userMana.searchByName.id },
        { id: 'phone', name: '手机号码', statId: this.CommonConfig.statData.userMana.searchByPhone.id }
      ],

      // 表格列
      tableColumns: [
        { name: '__index', field: '__index', label: '序号', align: 'left' },
        { name: 'number', field: 'number', label: '员工编号', align: 'left' },
        { name: 'name', field: 'name', label: '姓名', align: 'left' },
        { name: 'phone', field: 'phone', label: '手机号码', align: 'left' },
        { name: 'email', field: 'email', label: '邮箱', align: 'left' },
        { name: 'roles', field: 'roles', label: '角色', align: 'left' },
        { name: 'gender', field: 'gender', label: '性别', align: 'left' },
        { name: 'post', field: 'post', label: '岗位', align: 'left' },
        { name: 'icCardNumber', field: 'icCardNumber', label: 'IC卡号', align: 'left' },
        { name: 'skillLevelCode', field: 'skillLevelCode', label: '技能水平', align: 'left' },
        { name: 'price', field: 'price', label: '维修单价', align: 'left' },
        { name: 'ownerName', field: 'ownerName', label: '创建人', align: 'left' },
        { name: 'createTime', field: 'createTime', label: '创建时间', align: 'left' },
        // { name: 'status', field: 'status', label: '状态', align: 'left' },
        { name: 'operations', field: 'operations', label: '操作', align: 'center' }
      ],
      // 用户数组
      users: [],

      // 选中的用户
      selectedUsers: [],

      // 表格正在加载
      isTableLoading: false,

      // 表格分页配置
      pagination: {
        // 当前页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      fileName: null, // 文件名（用于订阅）

      // 部门 tree
      departments: [],
      departmentsClone: [],
      // 状态 toggle 是否处于禁用状态
      // key 是员工 ID，值是 boolean
      // 操作 toggle 后应将该 toggle 禁用，然后再请求 API，并在请求完成后重新启用 toggle
      // 避免快速多次操作 toggle，导致 toggle 显示的状态与实际状态不符
      isStatusToggleDisabled: {},

      // 状态 toggle 为 true 时的 status 值
      statusToggleTrueVal: 1,
      // 状态 toggle 为 false 时的 status 值
      statusToggleFalseVal: 0,

      // 用户详情 dialog 相关数据
      userDetailDialog: {
        // 显示 dialog
        show: false,
        // 用于查看
        forView: false,
        // 用于创建
        forCreate: false,
        // 用于编辑
        forEdit: true,
        // 用户详情对象
        detail: {}
      },

      // 显示 "设置工位" dialog
      showWorkCenterSetting: false,

      // 显示 "设置角色" dialog
      showRoleSetting: false
    }
  },
  methods: {
    /**
     * 列举查询栏的所有选项
     */
    listQueryOptions: function () {
      this.isRoleOptionsLoading = true
      this.isPostOptionsLoading = true

      this.roleOptions = []
      // 角色
      roleDefineApi.listRoles()
        .then(data => {
          // 结构转换
          let transformed = data.map(datum => {
            return {
              value: datum.id,
              label: datum.name
            }
          })

          this.roleOptions.push(...transformed)
        })
        .finally(() => {
          this.isRoleOptionsLoading = false
        })

      // 岗位
      this.postOptions = []
      getDict('post', false)
        .then(data => {
          this.postOptions.push(...data.data)
        })
        .finally(() => {
          this.isPostOptionsLoading = false
        })
    },

    /**
     * 列举技能水平选项
     */
    listSkillLevelOptions: function () {
      getDict('skill_level', false)
        .then(data => {
          this.skillLevelOptions = data.data
        })
    },

    /**
     * 列举用户
     */
    listUsers: function () {
      this.isTableLoading = true
      this.users = []
      this.selectedUsers = []

      userManageApi.listUsers(this.pagination.page, this.pagination.rowsPerPage, this.queryParams)
        .then(data => {
          data.list.forEach(item => {
            if (item.email === '') {
              item.email = '--'
            }
          })
          this.users = data.list
          this.pagination.rowsNumber = data.total
        })
        .finally(() => {
          this.isTableLoading = false
        })
    },

    /**
     * 根据用户状态推算 toggle 应显示的 tooltip 文字
     * @param statusCode 状态 code
     * @returns {string}
     */
    getStatusToggleTip: function (statusCode) {
      return statusCode === 0 ? '启用' : '禁用'
    },

    /**
     * 根据角色对象数组获取拼接的角色名
     * @param roles 角色对象数组
     * @return {string} 拼接的角色名
     */
    getRoleNamesByRoles: function (roles) {
      let names = ''

      // 最多显示 2 个 role
      const maxCount = 2
      for (let i = 0; i < maxCount; i++) {
        let role = roles[i]
        if (role === undefined) {
          break
        }
        names += ', ' + this.$_getOptionLabelByValue('roleOptions', role.id)
      }
      names = names.substr(2)

      // 若多于 2 个，则显示 "..."
      if (roles.length > maxCount) {
        names += ' ...'
      }

      return names
    },

    /**
     * 根据角色对象数组获取拼接的角色名
     * @param roles 角色对象数组
     * @return {string} 拼接的角色名
     * 过长时的tooltip
     */
    tooltipRoleNamesByRoles (roles) {
      let names = ''

      for (let i = 0; i < roles.length; i++) {
        let role = roles[i]
        if (role === undefined) {
          break
        }
        names += ', ' + this.$_getOptionLabelByValue('roleOptions', role.id)
      }
      names = names.substr(2)

      return names
    },

    /**
     * 根据岗位 code 获取岗位名称
     * @param postCode 岗位 code
     * @return {string} 岗位名称
     */
    getPostNameByCode: function (postCode) {
      return this.$_getOptionLabelByValue('postOptions', postCode)
    },

    /**
     * 根据状态 code 获取状态名称
     * @param statusCode 状态 code
     * @return {string} 状态名称
     */
    getStatusNameByCode: function (statusCode) {
      return this.$_getOptionLabelByValue('statusOptions', statusCode)
    },

    /**
     * 根据性别 code 获取性别名称
     * @param genderCode 性别 code
     * @return {string} 性别名称
     */
    getGenderNameByCode: function (genderCode) {
      return this.$_getOptionLabelByValue('genderOptions', genderCode)
    },

    /**
     * 根据 select options 的 value 获取 label
     * @param varName options 的变量名
     * @param value option 的 value
     * @return {string} 存在该 option，则返回其 label，否则返回空字符串
     */
    $_getOptionLabelByValue: function (varName, value) {
      if (value === null || value === undefined) {
        return ''
      }

      let options = this[varName].filter(option => {
        return option.value === value
      })
      if (options.length === 0) {
        return ''
      }

      return options[0].label
    },

    /**
     * on 分页组件的每页条数发生改变
     * @param val 每页条数
     */
    onPageSizeChange: function (val, page) {
      this.pagination.rowsPerPage = val
      page && (this.pagination.page = page)
      this.listUsers()
    },

    /**
     * on 分页组件的页码发生改变
     * @param val 页码
     */
    onPageChange: function (val) {
      this.pagination.page = val
      this.listUsers()
    },

    /**
     * 获取部门 tree
     */
    getDepartmentsTree: function () {
      userManageApi.getDepartmentsTree()
        .then(data => {
          this.departments = [...this.statUser, ...data]
          this.departmentsClone = data
        })
    },

    /**
     * on 部门被选中
     * @param item tree list item
     */
    onDepartmentSelect: function (item) {
      this.queryParams.departmentId = item.id
      this.listUsers()
    },

    /**
     * on 员工状态被 toggle
     * @param user 员工对象
     * @param status 状态
     */
    onStatusToggle: function (user, status) {
      this.$set(this.isStatusToggleDisabled, user.id, true)

      let successful = false
      userManageApi.toggleUserStatus(user.id, status)
        .then(resp => {
          successful = resp.success
        })
        .finally(() => {
          this.$set(this.isStatusToggleDisabled, user.id, false)
        })

      if (successful) {
        // 请求出错时，恢复 toggle 到切换前的状态
        user.status = status === this.statusToggleTrueVal ? this.statusToggleFalseVal
          : this.statusToggleTrueVal
      }
    },

    /**
     * on 员工删除按钮被点击
     * @param id 员工 ID
     */
    onDeleteClick: function (id) {
      this.$utils.showMessage('icontubiao-28', '确定要删除这个员工吗？', () => {
        this.getBindList([id])
        // this.deleteUser([id])
      }, true)
    },
    getBindList (ids, showDetail = false) {
      const type = [{
        key: 'DEVICE',
        label: '人机绑定'
      }, {
        key: 'WORK_ORDER',
        label: '加工工单'
      }, {
        key: 'QUALITY_CONTROL_ORDER',
        label: '质检工单'
      }, {
        key: 'REPAIR_ORDER',
        label: '维修工单'
      }, {
        key: 'MAINTENANCE_ORDER',
        label: '保养工单'
      }, {
        key: 'MAINTENANCE_SCHEDULE',
        label: '保养计划'
      }]
      userManageApi.getUserBindList(ids).then(res => {
        if (res.length) {
          const list = _.groupBy(res[0].binds, 'bindTypes')
          let message = '<div style="overflow-y: auto;max-height: 50vh" class="scrollbar">'
          if (showDetail) {
            if (list['DEVICE']) {
              console.log(list['DEVICE'])
              const bindList = _.join(_.map(list['DEVICE'], 'bindNumber'), '、')
              message += `${bindList}`
            } else {
              this.$message.warning('该人员无人机绑定在绑信息')
            }
          } else {
            type.forEach(item => {
              if (list[item.key]) {
                const bindList = _.join(_.map(list[item.key], 'bindNumber'), '、')
                message += `<span style="font-weight: bold">${item.label}：</span>${bindList}<br/>`
              }
            })
          }
          // message += '该人员数据被占用，请解除后再删除。<br/>'
          message += '</div>'
          if (showDetail) {
            if (list['DEVICE']) {
              this.$q.dialog({
                title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>人机绑定在绑信息</p>`,
                html: true,
                message: message,
                cancel: {
                  unelevated: true,
                  outline: true,
                  label: '取消'
                },
                ok: {
                  unelevated: true,
                  label: '一键清除'
                }
              }).onOk(() => {
                this.delBindList(ids[0])
              })
            }
          } else {
            this.$q.dialog({
              title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          该人员数据被占用，请解除后再删除</p>`,
              html: true,
              message: message,
              ok: {
                unelevated: true,
                label: '确认'
              }
            })
          }
        } else {
          showDetail && this.$message.warning('该人员无人机绑定在绑信息')
          !showDetail && this.deleteUser(ids[0])
        }
        console.log(res)
      })
    },
    delBindList (ids) {
      this.$q.loading.show()
      userManageApi.delUserBindList(ids).then(res => {
        if (res.code + '' === '1200') {
          this.$message.success('清除在绑信息成功')
          this.listUsers()
        }
      }).finally(() => {
        this.$q.loading.hide()
      })
    },
    /**
     * 删除员工
     * @param id 员工 ID
     */
    deleteUser: function (id) {
      userManageApi.deleteUser(id)
        .then(() => {
          this.listUsers()
          this.$message.success('删除成功')
        })
    },

    /**
     * on 查看用户按钮被点击
     * @param user 用户对象
     */
    onViewUserClick: function (user) {
      Object.assign(this.userDetailDialog, { forView: true, forCreate: false, forEdit: false })
      this.userDetailDialog.detail = user
      this.$refs.userDetail.showDialog(user)
    },

    /**
     * on 添加用户按钮被点击
     */
    onCreateUserClick: function () {
      Object.assign(this.userDetailDialog, { forView: false, forCreate: true, forEdit: false })
      this.userDetailDialog.show = true
      this.userDetailDialog.detail = { department: { id: this.queryParams.departmentId } }
    },

    /**
     * on 编辑用户按钮被点击
     * @param user 用户对象
     */
    onEditUserClick: function (user) {
      Object.assign(this.userDetailDialog, { forView: false, forCreate: false, forEdit: true })
      this.userDetailDialog.show = true
      this.userDetailDialog.detail = user
    },

    /**
     * on 工位设置成功
     */
    onWorkCentersSet: function () {
      this.showWorkCenterSetting = false
      this.listUsers()
    },

    /**
     * on 角色设置成功
     */
    onRolesSet: function () {
      this.showRoleSetting = false
      this.listUsers()
    },

    /**
     * 重置搜索栏
     */
    resetSearch: function () {
      this.queryParams.departmentId = null
      this.queryParams.role = 'all'
      this.queryParams.post = 'all'
      this.queryParams.status = null
    },

    /**
     * on 关闭 detail dialog
     */
    onDetailClose: function () {
      this.userDetailDialog.show = false
      this.userDetailDialog.detail = {}
    },

    /**
     * on 创建 / 编辑提交完毕
     */
    onDetailSubmitted: function () {
      this.userDetailDialog.show = false
      this.listUsers()
    },

    /**
     * on 关键字搜索
     * 按筛选条件 + 关键字进行列举
     */
    onSearchByKeyword: function (searchBy, keyword) {
      this.pagination.page = 1
      this.queryParams.searchBy = searchBy.id
      this.queryParams.keyword = keyword
      this.listUsers()
    },

    /**
     * on 筛选搜索
     * 按筛选条件进行列举
     */
    onSearchByFilters: function () {
      this.pagination.page = 1
      // this.queryParams.searchBy = ''
      // this.queryParams.keyword = ''
      this.listUsers()
    },

    /**
     * 重置搜索条件
     */
    clearSearchVal () {
      this.queryParams.searchBy = null
      this.queryParams.keyword = null
      this.pagination.page = 1
      this.listUsers()
    },

    /**
     * on 批量删除按钮被点击
     */
    onBatchDeleteClick: function () {
      this.$utils.showMessage('icontubiao-28', '确定要删除这些用户吗？', () => {
        let userIds = this.selectedUsers.map(o => o.id)
        userManageApi.batchDeleteUsers(userIds).then(() => {
          this.$message.success('删除成功')

          this.listUsers()
        })
      }, true)
    }
  },
  created () {
    this.listQueryOptions()
    this.listSkillLevelOptions()
    this.getDepartmentsTree()
    this.listUsers()
  }
}
</script>

<style scoped lang="stylus">
  .user-mana {
    .toolbar .form-inline {
      display flex
      justify-content space-between
      align-items flex-start
      padding-bottom 0

      .box {
        display flex
        flex-wrap wrap
        justify-content flex-start
        align-items center
      }

      &.top {
        .left.box .select {
          margin 0 20px 20px 0
        }

        .right.box {
          flex-wrap nowrap
        }
      }

      &.bottom {
        .left.box .btn {
          margin: 0 10px 16px 0
        }

        .right.box {
          flex-wrap nowrap

          .quik-search {
            margin-right 10px
          }
        }
      }
    }

    .users-table {
      margin-top 4px
      margin-bottom 40px

      .user-status {
        .indicator {
          display inline-block
          border-radius 50%
          height 10px
          width 10px
          margin-right 2px

          &.positive {
            background $positive
          }

          &.negative {
            background $negative
          }
        }

        .text {
          &.positive {
            color $positive
          }

          &.negative {
            color $negative
          }
        }

      }

      .operations {
        width 200px

        .btn-group {
          display flex
          justify-content center
          align-items center
        }
      }
    }

    /deep/ .fold .right-part {
      padding-top 0
      padding-bottom 20px
    }
  }
</style>
